package com.shangye.core;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责处理与某个客户端的一次HTTP交互。
 * 由于HTTP协议要求客户端和服务端采取一问一答的原则，因此这里处理与客户端的一次交互规划
 * 为三个步骤:
 * 1:解析请求(将客户端发送过来的请求内容读取到)
 * 2:处理请求(根据请求内容进行对应的处理)
 * 3:发送响应(将处理结果回馈给浏览器)
 * 断开连接
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    private String method;
    private String uri;
    private String protocol;
    private Map headers = new HashMap();

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            //  读取请求行
            String line = redLine();
            System.out.println("请求行：" + line);
            //  解析请求行：
            String[] split = line.split("\\s");
            method = split[0];
            uri = split[1];
            protocol = split[2];
            System.out.println("请求方式：" + method);
            System.out.println("请求路径：" + uri);
            System.out.println("协议版本：" + protocol);


            while (true){
                line = redLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println("消息头：" + line);
                split = line.split(": ");
                headers.put(split[0],split[1]);
            }
            System.out.println("消息头MAP：" + headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String redLine() throws Exception {

        InputStream is = socket.getInputStream();

        char pre = 'a', cur = 'a';
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d = is.read()) != -1) {
            cur = (char) d;
            if (pre == 13 && cur == 10) {
                break;
            } else {
                pre = cur;
                builder.append(cur);
            }
        }
        String line = builder.toString().trim();
        return line;
    }
}
